package com.antaohua.tools.shares.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.antaohua.tools.api.domain.APIResultDomain;
import com.antaohua.tools.api.service.InterfaceCallService;
import com.antaohua.tools.framework.base.exception.DeleteEntityException;
import com.antaohua.tools.framework.base.exception.InsertEntityException;
import com.antaohua.tools.framework.base.exception.QureyEntityException;
import com.antaohua.tools.framework.base.service.BaseService;
import com.antaohua.tools.shares.entity.SharesStockEntity;
import com.antaohua.tools.shares.service.SharesStockService;
@Service
@Transactional
public class SharesStockServiceImpl extends BaseService<SharesStockEntity> implements SharesStockService{

	String eL = "[0-9]{4}-[0-9]{2}-[0-9]{2}";
	
	@Autowired
	private InterfaceCallService callService;
	
	@Override
	public void updateAll(String indexCode) throws IOException,InsertEntityException, QureyEntityException,DeleteEntityException, ParseException {
		
		dao.deleteByProperty("market", indexCode);
		
		Map<String, String> parameters = new HashMap<>();
		Pattern p = Pattern.compile(eL);
		int pageNm = 1,pagesize = 1;
		
		do {
			parameters.put("market", "sz");
			parameters.put("page", String.valueOf(pageNm));
			APIResultDomain result = callService.get("stocklist", parameters);
			JSONObject jsonObject = JSONObject.parseObject(result.getData());
			JSONArray array = jsonObject.getJSONArray("contentlist");
			for (int i = 0; i < array.size(); i++) {
				JSONObject itme = array.getJSONObject(i);
				System.out.println(itme);
				SharesStockEntity stock = new SharesStockEntity();
				stock.setCode(itme.getString("code"));
				stock.setCurrcapital(itme.get("currcapital")==null?null:itme.getString("currcapital").length()>0?itme.getDouble("currcapital"):null);
				stock.setListing_date(itme.get("listing_date")==null?null:p.matcher(itme.getString("listing_date")).matches()  ?DateUtils.parseDate(itme.getString("listing_date"), "yyyy-MM-dd"):null);
				stock.setMarket(itme.get("market")==null?null:itme.getString("market"));
				stock.setMgjzc(itme.get("mgjzc")==null?null:itme.getDouble("mgjzc"));
				stock.setName(itme.getString("name"));
				stock.setPingyin(itme.get("pinyin")==null?null:itme.getString("pinyin"));
				stock.setProfit_four(itme.get("profit_four")==null?null:itme.getDouble("profit_four"));
				stock.setTotalcapital(itme.get("totalcapital")==null?null:itme.getDouble("totalcapital"));
				dao.save(stock);
			}
			pageNm ++;
		} while (pageNm<=pagesize);
	
	}

	
	
	
}
